from django.core.exceptions import ValidationError
from django.db import connection

from app.decorator import jwt_auth
from app.model.table_goods_class import TableGoodsClass
from libs.common import success, is_empty_str, error
from libs.db import DB
from libs.form import RawJsonForm


@jwt_auth
def goods_class_list_v2(request, auth):
    form = RawJsonForm(request.body)
    is_fast_food = form.get_int('is_fast_food')
    shop_id = auth.get('shop_id')
    goods_class_arr = []
    try:
        goods_class_parent_dict = {}
        with connection.cursor() as cursor:
            where_map = {'shop_id': shop_id}
            if is_fast_food == 1:
                dh = DB('table_goods', conn=cursor)
                goods_class_rows = dh.find([('class_id', 'class_id', 'distinct')],
                                           {'shoper_id': shop_id, 'is_fast_food > 0': None})#'is_fast_food': 1
                cls_id_arr = []
                for goods_class_row in goods_class_rows:
                    cls_id_arr.append(str(goods_class_row.get('class_id')))
                goods_class_arr = ()
                if len(cls_id_arr) > 0:
                    where_map = {
                        'id in ({})'.format(','.join(cls_id_arr)): None
                    }
                    fields = ['id', 'class_name']
                    goods_class_dh = DB('table_goods_class', conn=cursor)
                    goods_class_arr = goods_class_dh.find(fields, where=where_map)
            else:
                fields = ['id', 'class_name', 'parent_id']
                dh = DB('table_goods_class', conn=cursor)
                rows = dh.order_by('parent_id').find(fields, where=where_map)
                for row in rows:
                    class_id = row.get('id')
                    class_parent_id = row.get('parent_id')
                    class_name = row.get('class_name')
                    if is_fast_food == 1:
                        if class_parent_id == 0:
                            goods_class_parent_dict[class_id] = {
                                'id': class_id,
                                'class_name': class_name,
                            }
                    else:
                        if class_parent_id == 0:
                            goods_class_parent_dict[class_id] = {
                                'id': class_id,
                                'class_name': class_name,
                                'children': []
                            }
                        else:
                            class_data = goods_class_parent_dict.get(class_parent_id, None)
                            if class_data is not None:
                                class_data['children'].append({
                                    'id': class_id,
                                    'class_name': class_name
                                })
                goods_class_arr = list(goods_class_parent_dict.values())
    except Exception as e:
        print(e.args)
    return success(goods_class_arr)


@jwt_auth
def add_goods_class(request, auth):
    form = RawJsonForm(request.body)
    class_name = form.get('class_name')
    if is_empty_str(class_name):
        return error('分类名称不能为空')
    shop_id = auth.get('shop_id')
    parent_id = form.get_int('parent_id')

    db = DB('table_goods_class')
    row = db.one(['id'], {
        'parent_id': parent_id,
        'class_name': class_name,
        'shop_id': shop_id,
    })
    if row.get('id', 0) > 0:
        return error('分类名已存在')

    goods_class = TableGoodsClass()
    goods_class.class_name = class_name
    goods_class.parent_id = parent_id
    goods_class.shop_id = shop_id
    try:
        goods_class.full_clean()
        goods_class.save()
    except ValidationError as e:
        msg_arr = []
        for (k, item) in e.message_dict.items():
            msg_arr.append('{}:{}'.format(k, ';'.join(item)))
        return error(';'.join(msg_arr))
    return success()


@jwt_auth
def update_goods_class(request, auth):
    form = RawJsonForm(request.body)
    class_id = form.get_int('id')
    shop_id = auth.get('shop_id')
    if class_id == 0:
        return error('无效的分类ID')
    class_name = form.get('class_name')
    if is_empty_str(class_name):
        return error('分类名称不能为空')
    try:
        new_data = {
            'class_name': class_name
        }
        parent_id = form.get_int('parent_id', None)
        if parent_id is not None:
            new_data['parent_id'] = parent_id
        TableGoodsClass.objects.filter(id=class_id, shop_id=shop_id).update(**new_data)
    except Exception as e:
        print(e.args)
        return error()
    return success()


@jwt_auth
def del_goods_class(request, auth):
    form = RawJsonForm(request.body)
    class_id = form.get_int('id')
    shop_id = auth.get('shop_id')
    if class_id == 0:
        return error('无效的分类ID')
    try:
        TableGoodsClass.objects.filter(id=class_id, shop_id=shop_id).delete()
    except Exception as e:
        print(e.args)
        return error()
    return success()
